﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 添加工艺工序
    /// </summary>
    public class CreateOperationHandler : IRequestHandler<CreateOperationCommand, Result>
    {
        /// <summary>
        /// mapper类
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 工艺工序表
        /// </summary>
        private readonly IBaseRepository<ProcessLineOperations> _processLineOperationRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateOperationHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processLineOperationRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreateOperationHandler(IBaseRepository<ProcessLineOperations> processLineOperationRepository,
                                      ILogger<CreateOperationHandler> logger,
                                      IMapper mapper)
        {
            _processLineOperationRepository = processLineOperationRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加工艺路线工序
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateOperationCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //条件转换为类
                var operation = _mapper.Map<ProcessLineOperations>(request);
                var res = await _processLineOperationRepository.Add(operation);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加工艺路线工序成功";
                }

            }
            catch (Exception ex)
            {
                result.Msg = "添加工艺路线工序异常" + ex.Message;
                _logger.LogError("添加工艺路线工序异常" + ex.Message);
            }
            return result;
        }
    }
}
